<template>
  <div class="category-management-page">
    <div class="page-header">
      <h2>分类管理</h2>
      <el-divider/>
    </div>
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form inline :model="queryParams" ref="queryFormRef">
        <el-form-item label="关键字">
          <el-input
              placeholder="请输入分类名称"
              v-model="queryParams.keywords"
              clearable
              @keyup.enter="handleQuery"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              :icon="Search"
              @click="handleQuery"
          >
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
              :icon="Refresh"
              @click="resetQuery"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button
          type="primary"
          :icon="Plus"
          @click="openAddDialog"
      >
        分类新增
      </el-button>
    </div>
    <!-- 分类列表 -->
    <el-card class="content-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">分类列表</span>
          <el-badge :value="categoryPage.list.length" type="success"/>
        </div>
      </template>
      <el-table
          :data="categoryPage.list"
          v-loading="loading"
          border
          highlight-current-row
          :row-class-name="tableRowClassName"
      >
        <el-table-column prop="categoryId" label="编号"  align="center"/>
        <el-table-column prop="name" label="名称">
          <template #default="scope">
            <el-tag>{{ scope.row.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="图标">
          <template #default="scope">
           <el-icon>
             <el-image :src="scope.row.icon"></el-image>
           </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述"/>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button
                  type="text"
                  size="small"
                  :icon="EditPen"
                  @click="handleModify(scope.row)"
                  class="edit-btn"
              >
                修改
              </el-button>
              <el-button
                  type="text"
                  size="small"
                  :icon="Delete"
                  @click="handleDelete(scope.row.categoryId)"
                  class="delete-btn"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="queryParams.pageNum"
          :page-sizes="[8, 16, 32, 64]"
          v-model:page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <!-- 分类编辑对话框 -->
    <el-dialog
        :title="isAdd ? '新增分类' : '修改分类'"
        v-model="dialogVisible"
        width="500px"
        :close-on-click-modal="false"
        @close="handleDialogClose"
    >
      <el-form
          :model="currentCategory"
          ref="categoryFormRef"
          :rules="rules"
          label-width="80px"
          size="default"
      >
        <el-form-item label="图标">
          <el-upload
              class="avatar-uploader"
              :action="$fileUpload"
              :show-file-list="false"
              :data="{sceneCode:'social:post:category'}"
              :headers="$getHeaders"
              :on-success="handleAvatarSuccess"
          >
            <img v-if="currentCategory.icon" :src="currentCategory.icon" class="avatar" alt="回显失败"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类名" prop="name">
          <el-input
              v-model="currentCategory.name"
              placeholder="请输入分类名称"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
              v-model="currentCategory.parentId"
              :options="parentTree"
              :props="props"
              @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="层级" prop="level">
          <el-input v-model="currentCategory.level" placeholder="请输入层级"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
              type="textarea"
              v-model="currentCategory.description"
              placeholder="请输入分类描述"
              :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitCategoryForm">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, reactive, onMounted, watch} from 'vue';
import {Search, Refresh, Delete, EditPen, Plus} from '@element-plus/icons-vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import {
  reqAddPostCategory,
  reqDeletePostCategoryById,
  reqGetPostCategoryById,
  reqUpdatePostCategory,
  reqGetCategoryTagCount, reqGetCategooryParentList, reqGetPostCategoryPage
} from '@/api/social/post';

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 8,
  keywords: ""
});

// 状态管理
const loading = ref<boolean>(true);
const dialogVisible = ref(false);
const isAdd = ref(true);
const categoryFormRef = ref<FormInstance>();
const queryFormRef = ref<FormInstance>();
let parentTree = ref([]);

// 当前操作的分类
const currentCategory = reactive({
  categoryId: undefined,
  name: "",
  description: "",
  parentId: undefined,
  icon: "",
  level: ""
});
let categoryPage = reactive({
  pageNum: 1,
  list: [],
  total: 0
})
//配置
const props = {
  label: 'name',
  children: 'children',
  value: 'categoryId',
  emitPath: false,
  checkStrictly: true
}
// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    {required: true, message: "请输入分类名称", trigger: "blur"},
    {min: 2, max: 15, message: "分类名称长度在 2 到 15 个字符", trigger: "blur"}
  ]
});

// 获取分类列表
const getCategoryList = () => {
  loading.value = true;
  reqGetPostCategoryPage(queryParams).then((res) => {
    Object.assign(categoryPage, res.data)
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};
let getCategoryParentTree = async () => {
  let res = await reqGetCategooryParentList()
  parentTree.value = res.data
};
let handleAvatarSuccess=(res:any)=>{
  currentCategory.icon = res.data.visitPath
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  getCategoryList();
};

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  getCategoryList();
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size;
  getCategoryList();
};

// 处理页码变化
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  getCategoryList();
};

// 打开新增对话框
const openAddDialog = () => {
  isAdd.value = true;
  Object.assign(currentCategory, {
    categoryId: undefined,
    name: "",
    description: "",
    parentId: undefined,
    icon: "",
    level: ""
  });
  dialogVisible.value = true;
};

// 处理修改
const handleModify = (row: any) => {
  reqGetPostCategoryById(row.categoryId).then((res) => {
    Object.assign(currentCategory, res.data);
    isAdd.value = false;
    dialogVisible.value = true;
  });
};

// 处理删除
const handleDelete = (categoryId: string) => {
  // 检查是否有关联的标签
  const category = categoryPage.list.find((item: any) => item.categoryId === categoryId);

  if (category && category.tagCount > 0) {
    ElMessage.warning("该分类下有关联标签，不能删除");
    return;
  }

  ElMessageBox.confirm(
      "确定要删除这个分类吗？删除后不可恢复。",
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      } as string
  ).then(() => {
    reqDeletePostCategoryById(categoryId).then(() => {
      getCategoryList();
    });
  }).catch(() => {
    ElMessage.info("已取消删除");
  });
};

// 提交表单
const submitCategoryForm = async () => {
  if (!categoryFormRef.value) return;

  try {
    await categoryFormRef.value.validate();

    if (isAdd.value) {
      await reqAddPostCategory(currentCategory);
    } else {
      await reqUpdatePostCategory(currentCategory);
    }

    dialogVisible.value = false;
    getCategoryList();
  } catch (error) {
    // 表单验证失败
    return;
  }
};

// 处理对话框关闭
const handleDialogClose = () => {
  categoryFormRef.value?.resetFields();
};

// 表格行样式
const tableRowClassName = ({rowIndex}: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
};

// 初始化
onMounted(() => {
  getCategoryList();
  getCategoryParentTree()
});

// 监听查询参数变化
watch([() => queryParams.pageNum, () => queryParams.pageSize], () => {
  getCategoryList();
});
</script>

<style scoped>
.category-management-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #1f2329;
  margin-bottom: 10px;
}

.search-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.action-buttons {
  margin-bottom: 20px;
}

.content-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.content-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: 600;
  font-size: 16px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.edit-btn {
  color: #409eff;
}

.edit-btn:hover {
  color: #66b1ff;
  background-color: #ecf5ff;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f78989;
  background-color: #fef0f0;
}

.even-row {
  background-color: #f9fafb;
}

.odd-row {
  background-color: #ffffff;
}

::v-deep .el-table__row:hover > td {
  background-color: #f0f7ff !important;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
